#!/usr/bin/bash
# Author : Raman Rawat
# Usage
# Copies the source directory and search & replace all r&R pair strings in file contents and file/dir names also.
# ./BitteGerne.sh srcDir tgtDir r1 Rep1 [r2 Rep2 r3 Rep3 ]
# srcDir == Source directory to copy without ending /
# tgtDir == Target directory to copy without ending /
# r1 == first string to replace. Enclose in "", if it has space in between
# Rep1 == first REPLACEMENT string (Enclose in "", if it has space in between)
#  followed by pair of r and R.
#  All r & R pairs are used to rename files & directories.
#=========================================
# Dependencies
#  	tmv shell script. Call tmv --help for details. MUST BE In /usr/bin and not /usr/local/bin
#  	ReplaceTextInFile.awk 
#  	BitteGerne.awk -- NOT ANYMORE.
#=========================================
# TODO
# 1 Handle trailing / at the end of the directory name.
#DIRECTORY="/home/jennor/"
#echo ${DIRECTORY%/} # Remove any trailing slash

# CurrentWorkingDir
cwd=$PWD

# awk files must in the same dir as this script
repTextAWK=`dirname $0`/ReplaceTextInFile.awk
BitteGerneAWK=`dirname $0`/BitteGerne.awk
tmpDir=/usr/tmp/$2
if [ ! -d  $tmpDir ] ; then 
	mkdir $tmpDir
fi


Usage()
{
echo "Usage :"
echo " ./BitteGerne.sh srcDir tgtDir r1 Rep1 [r2 Rep2 r3 Rep3 ...... ] "
echo " srcDir == Source directory to copy without ending /"
echo " tgtDir == Target directory to copy without ending /"
echo " r1 == first string to replace"
echo " Rep1 == first REPLACEMENT string"
echo "  followed by pairs of r and R."

exit 1
}

# Function to move the input file to temp directory
BackupFile()
{
if [ -n "$1" ] ; then
if [ -f  $1 ] ; then 
	echo "Backing up $1 to $tmpDir"
	mv -f $1  $tmpDir
fi
fi
}

# Function to append the file in temp dir to actual file
# $1 - file to append
# $2 FileName which is to be appended to $1
RestoreFile()
{
if [ -f $tmpDir/$2 ] ; then 
	tail +5 $1 >> $tmpDir/$2
	mv $tmpDir/$2  $1
	echo "Restoring " $1
fi
}

# if number of args are less than 4 exit
if [ $# -lt 4 ] ; then
	echo " Missing arguments:" 
	Usage
fi
# Note current workind directory
cwd=$PWD
echo "In dir "$PWD

idCardH=$2/IdentityCard/IdentityCard.h
dicoFile=$2/CNext/dico/$2.dico
iidFile=$2/CNext/dico/$2.iid

# clean up any previous result
rm -f FilesToCopy.* DirsToCopy.*

# if the first argument is NOT a directory then exit
if [ -n $1 ] && [ -d $1 ] 
then 
	echo "Copying dir " $1 
else
	echo "Dir " $1 "doesn't exist."
Usage
fi

# if the second argument not NULL and is a directory
if [ -n $2 ] && [ -d $2 ] ; then 
	chmod -R 755 $2
else
	echo "Creating dir " $2 
	mkdir $2
	chmod -R 755 $2
fi

# find list of all files in dir 2 
cd $1
echo "In dir "$1

fileList=$cwd/FilesToCopy.txt
dirList=$cwd/DirsToCopy.txt

# make list of all files & dirs in $1
#FilesToCopy.txt format : FullPath(File/Dir)	ParentDir	FileName/DirName
find . -type f -printf "\n%p %h %f " > $fileList
find . -type d -printf "\n%p %h %f " > $dirList

cd $cwd
echo "In dir "$PWD
echo Backup Time Taken : $SECONDS

# recursively copy dir 1 to dir 2
cp -R $1/* -t $2
chmod -R 755 $2

#for i in 'cat NewFileNames.txt' # for loop executing a command and iterating over the results
#do
#	sed 's/XXX/YYY/g'  $i
#done
# for ((i =1 ; i <= 0; i++ )) # for loop example with integer++

# go to target dir
cd $2
echo "In dir "$PWD

# cmdLine arguments to this script
i=0
# for file in $@ ; do 
	# i=`expr $i + 1` #echo "arg " $i   ":" $file
# done

cp -f $dirList $dirList.txt

#================================================================================
# replace text in files with r & R strings input in cmdLine arguments
#================================================================================
# delete all CONSECUTIVE blank lines from file except the first
#sedArg="" 
#sedArg=" -e '/./,/^$/!d' "
#sedArg=" -e '/^$/N;/\n$/N;//D' "

# NOTE BASH_ARGV[] stores arguments in reverse order
# create arguments for sed: -e 's/r1/R1/g' -e 's/r2/R2/g' -e 's/r3/R3/g' -e 's/r4/R4/g' .........
# sed '/foo/ s/foo/bar/g' filename   # executes more quickly

j=0
for ((i=${BASH_ARGC}-3 ; i > 0; i-=2))
do 
	let j=i-1
	
	echo "Replacing " ${BASH_ARGV[$i]} "with " ${BASH_ARGV[$j]}
	# replace the contents of the files
	#awk -v r="${BASH_ARGV[$i]}" -v Replacement="${BASH_ARGV[$j]}" -f $repTextAWK $fileList

	# recurively create arguments for sed
	sedArg="$sedArg -e '/${BASH_ARGV[$i]}/ s/${BASH_ARGV[$i]}/${BASH_ARGV[$j]}/g' "

	# Change the dirNames in the $dirList.txt file
	sed "/${BASH_ARGV[$i]}/ s/${BASH_ARGV[$i]}/${BASH_ARGV[$j]}/g"  $dirList.txt > $dirList.tmp
	mv $dirList.tmp $dirList.txt
done

echo $0 Replace Pattern Composition time : $SECONDS

#================================================================================
# finally call the sed cmd with ALL pattern/replacement on all the files
# Remove blank lines
#================================================================================
# cat -s doesn't work from awk so create a temporary shell script in parent dir. it should not be found in find command below
beautifySHELL=../Beautify.sh
echo "#!/bin/bash" > $beautifySHELL
echo "#This is a generated file do not edit" >> $beautifySHELL

echo Replacing as per Sed arguments $sedArg

for i in `find . -type f` # for loop executing a command and iterating over the results
do
	#echo Processing File  $i
	sedCmd="sed -e '/./,/^$/!d' $sedArg $i > $i.tmp"
	#sed -e '/./,/^$/!d' $i > $i.tmp
	echo $sedCmd >> $beautifySHELL
	#eval $sedCmd
	#mv -f $i.tmp $i
	echo "mv -f $i.tmp $i" >> $beautifySHELL
done

# To avoid awk: warning: escape sequence `\?' treated as plain `?' : Ans \? should be passed as \\?
i=1
j=0
utlArg="-e 's/${BASH_ARGV[$i]}/${BASH_ARGV[$j]}/g' "
utlArg=${utlArg//\?/\\\\?}
#echo "Utl text replacement" $utlArg
#awk -v r="$utlArg" -f $BitteGerneAWK $fileList >> $beautifySHELL

echo $0 Replace Text time : $SECONDS

#chmod 755 $beautifySHELL
#bash -v $beautifySHELL

astyle --quiet --style=ansi --suffix=none --recursive --lineend=linux *.cpp *.h *.cs
echo $0 After astyle : $SECONDS
#================================================================================
# rename the files & dirs. requires the tmv script. Call tmv --help for details
#================================================================================

sedArg="find . -depth | tmv -q $sedArg"
echo "rename the files & dirs $sedArg"
eval $sedArg		# run the string as a command

echo $0 Rename dir time : $SECONDS

#j=0
##for ((i=${BASH_ARGC}-3 ; i > 0; i-=2))
## for loop commented out
#for ((i=-1 ; i > 0; i-=2))
#do 
#	j=`expr i-1`
#	echo "Renaming " ${BASH_ARGV[$i]} "with " ${BASH_ARGV[$j]}
#	# rename the files 
#	awk -v r="${BASH_ARGV[$i]}" -v Replacement="${BASH_ARGV[$j]}" -f $BitteGerneAWK $fileList
#	# rename the dirs 
#	awk -v r="${BASH_ARGV[$i]}" -v Replacement="${BASH_ARGV[$j]}" -f $BitteGerneAWK $dirList
#	# regenerate the file and dir list
#	find . -type f  -printf "\n%p %h \t %f" > $fileList
#	find . -type d -printf "\n%p %h \t %f" > $dirList
#done
#

cd $cwd
 
# make list of new files copied

# Create batch file to add new files to SCM
cd $2
#find . -type f | awk ' BEGIN { print "set OPER_CMD=adl_mk_elem "}{ if (length($0) > 0) { print "%OPER_CMD% " $1 }}' > $filesCopied.bat
#find . -type d | awk ' BEGIN { print "set OPER_CMD=adl_mk_dir " }{ if (length($0) > 0) { print "%OPER_CMD% " $1 }}' > $dirsCopied.bat

cd $cwd

# The first input file will be processed first and then the 2nd input file
#awk '{ print "moving " $0 " to " $0 }' $fileList NewFileNames.txt
